import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert'; // json方法

class Store {
  final SharedPreferences _store;
  static Future<Store> getInstance() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    return Store._internal(preferences);
  }

  Store._internal(this._store);

  // 布尔值
  Future<void> saveBoolStatus(String key, bool value) async {
    await _store.setBool(key, value);
  }

  Future<bool> getBoolStatus(String key) async {
    return _store.getBool(key) ?? false;
  }

  // 字符串
  Future<void> saveString(String key, String value) async {
    await _store.setString(key, value);
  }

  Future<String?> getString(String key) async {
    return _store.getString(key);
  }

  // 整形
  Future<void> saveInt(String key, int value) async {
    await _store.setInt(key, value);
  }

  Future<int?> getInt(String key) async {
    return _store.getInt(key);
  }

  /// 根据key存储Map类型
  Future<bool> saveMap(String key, Map value) async {
    return _store.setString(key, json.encode(value));
  }

  Map getMap(String key) {
    String jsonStr = _store.getString(key) ?? "";
    return jsonStr.isEmpty ? {} : json.decode(jsonStr);
  }

  // 清除一个数据
  Future<bool> remove(String key) async {
    return _store.remove(key);
  }

  // 清空所有数据
  Future<bool?> clearAll() async {
    return _store.clear();
  }

  // 是否有某个key
  Future<bool?> hasKey(String key) async {
    return _store.containsKey(key);
  }
}
